<template lang="">
	<view class="good-publish">
		<u-line color="#002233" />
		<scroll-view
			scroll-y
			scroll-with-animation
			class="scroll"
		>
			<view class="publish-bar">
				<u-textarea
					v-model="title"
					placeholder="名称、品牌型号、入手渠道、转手原因等文字描述..."
					border="none"
				/>
				<view class="upload-box">
					<u-upload
						class="upload"
						:fileList="fileList1"
						@afterRead="afterRead"
						@delete="deletePic"
						name="1"
						:maxCount="1"
						:previewFullImage="true"
						uploadText="角度1"
					/>
					<u-upload
						class="upload"
						:fileList="fileList2"
						@afterRead="afterRead"
						@delete="deletePic"
						name="2"
						:maxCount="1"
						:previewFullImage="true"
						uploadText="角度2"
					/>
					<u-upload
						class="upload"
						:fileList="fileList3"
						@afterRead="afterRead"
						@delete="deletePic"
						name="3"
						:maxCount="1"
						:previewFullImage="true"
						uploadText="角度3"
					/>
					<u-upload
						class="upload"
						:fileList="fileList4"
						@afterRead="afterRead"
						@delete="deletePic"
						name="4"
						:maxCount="1"
						:previewFullImage="true"
						uploadText="其他"
					/>
				</view>
				<text>上传商品整体图和细节,最多4张;首图即为商品封面</text>
			</view>
			<u-line color="#3A62E9" />
			<view class="info-bar">
				<view class="title">
					<u-image
						src="https://skillgo.cn/image/charge/PublichGoodDetialr.png"
						width="48rpx"
						height="48rpx"
					/>
					<text class="infoshop">商品信息</text>
				</view>
				<view class="publInfo-table">
					<view class="table-row">
						<view class="text"><text>分类</text></view>
						<view
							class="button"
						>
							<scroll-btn
								:column="sortationList"
								@confirm="sortationAttrConfirm"
								initActive="0"
							/>
						</view>
					</view>
					<view
						class="table-row"
						v-for="(item, index) in attributes"
						:key="index"
					>
						<view class="text"><text>{{item && item.attributeName}}</text></view>
						<view
							class="button"
						>
							<scroll-btn
								:column="attributeList[index]"
								:myKey="index"
								@confirm="sortationConfirm"
							/>
						</view>
					</view>
				</view>
			</view>

			<u-line color="#002233" />
			<view class="price-info">
				<view class="true-price">
					<view class="image">
						<u-image
							src="https://skillgo.cn/image/charge/publichGood.png"
							width="48rpx"
							height="48rpx"
						/>
						<text class="leftsellprice">售价</text>
					</view>
					<view class="right-price">
						<text
							class="right"
							@click="priceClick"
						>
							￥{{price||"请输入售价"}}
						</text>
						<u-icon
							name="arrow-right"
							size="28rpx"
							color="#b5b5b5"
						/>
					</view>
				</view>
				<view class="old-price">
					<text class="left">原价</text>
					<text class="right">￥{{oldPrice||"请输入原价"}}</text>
				</view>
			</view>
		</scroll-view>
		<confirm-button
			class="cf-button"
			@publish="showModalPop"
		/>
		<u-modal
			:show="showModal"
			:title="title"
			:content='content'
			:asyncClose="true"
			@confirm="addGoods"
			:showCancelButton="true"
			class="modal"
			@cancel="cancelModal"
		/>
		<!-- <u-overlay :show="showPrice" :duration="400" :z-index ="999" :opacity="0.3" @click="showPrice = false">
			<u-input v-model="price" type="number" @tap.stop @confirm="showPrice = false" :focus="true"/>
		</u-overlay>  -->
		<u-popup
			:show="showPrice"
			@close="popClose"
			mode="center"
			:round="10"
		>
			<view class="pop">
				<input
					type="number"
					:password="false"
					v-model="price"
					placeholder="请输入价格"
				>
				<input
					type="number"
					v-model="oldPrice"
					placeholder="请输入原价"
					:password="false"
				>
			</view>
		</u-popup>
		<u-popup
			:show="showMall"
			mode="center"
			@close="closeModal"
			@open="open"
			closeOnClickOverlay
			class="pupImage"
		>
			<image
				src="https://skillgo.cn/mallpublish.jpg"
				style="width:450rpx;height:450rpx"
			/>
		</u-popup>
		<u-toast ref="uToast" />
	</view>
</template>
<script>

import confirmButton from './components/confirmButton.vue'
import { postGoodsPublish, getAllType, getAttributeByTypeId, addGoodsData } from '@/api/MallPages/goods.js'
import scrollBtn from './components/scrollBtn.vue'
import { getUserInfo } from '@/store/user.js'
import { getToken, setToken, removeToken } from '@/store/user'

export default {
  components: {
    confirmButton,
    scrollBtn
  },
  async created() {
    getApp().globalData.publishtime += 1
    if (getApp().globalData.publishtime >= 2) {
      this.showMall = false
    }
    const res = (await getAllType()).data

    this.sortationList.push(res.map(item => item.type))
    this.sortation = this.sortationList[ 0 ][ 0 ]

    const atr = (await getAttributeByTypeId({ belongingType: 1 })).data

    this.attributes = atr
    this.currentType = 1
    this.attributeList = atr && atr.map(item => {
      const list = []

      list.push(item.attributeValueList && item.attributeValueList.map(atr => atr.value))
      return list
    })
    this.valueList = new Array(atr.length).fill('未知')
    console.log(this.attributeList, '-----------')
    console.log(atr)

    this.userInfo = getUserInfo()
    console.log(this.userInfo, 'userInfo')

  },
  computed: {

  },
  data() {
    return {
      showMall: true,
      showmsg: true,
      bgColor: '#ffffff',
      fileList1: [],
      fileList2: [],
      fileList3: [],
      fileList4: [],
      sortationshow: false,
      sortation: '',
      sortationList: [],
      attributes: [],
      // 当前的内容数组
      column: this.sortationList,
      // 控制是否出现picker
      show: false,
      attributeList: [],
      // 控制当前picker的内容
      index: -1,
      valueList: [],
      userInfo: '',
      filePathList: [],
      // 当前的类型
      currentType: 1,
      detailDes: '',
      // 控制是否出现pop弹出层
      showModal: false,
      content: '是否确认发布',
      // 控制是否出现price修改框
      showPrice: false,
      price: '',
      oldPrice: '',
      title: ''
    }
  },
  methods: {
    popClose() {
      this.showPrice = false
      if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(this.price)) {
        this.price = '请输入正确价格'
      }
      if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(this.oldPrice)) {
        this.oldPrice = ''
      }
    },
    priceClick() {
      this.showPrice = true
      if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(this.price)) {
        this.price = ''
      }
    },
    showModalPop() {
      if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(this.price) || !/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(this.oldPrice)) {
        this.$refs.uToast.show({
          type: 'error',
          icon: false,
          title: '失败主题',
          message: '请正确输入价格！！！！',
          complete() {

          }
        })
        return
      }
      this.showModal = true
    },
    cancelModal() {
      this.showModal = false
      console.log('>>>??????')
    },
    async addGoods() {
      console.log(this.valueList)
      if (this.valueList.includes(undefined)) {
        this.showModal = false
        this.$refs.uToast.show({
          type: 'error',
          icon: false,
          title: '失败主题',
          message: '请输入所有商品信息',
          complete() {
          }
        })
        return
      }
      const _data = {
        picture: null,
        title: this.title,
        price: this.price,
        detailPicture1: null,
        detailPicture2: null,
        detailPicture3: null,
        detailPicture4: null,
        publisherId: getUserInfo().id,
        publisherName: getUserInfo().appNickName,
        publisherAvatar: getUserInfo().avatarUrl,
        releaseTime: null,
        collection: null,
        browse: null,
        detailDescription: this.detailDes,
        type: this.currentType,
        originalPrice: this.oldPrice,
        suggestedPrice: 2500,
        offShelf: 0,
        isDelete: 0
      }

      console.log(this.detailDes, 'hugygy')
      const commodityId = (await addGoodsData(_data)).data

      console.log(commodityId, 'commodityId')
      console.log(this.attributes)
      const data = this.attributes.map((item, index) => {
        return {
          'commodityId': commodityId,
          'attributeName': item.attributeName,
          'value': this.valueList[ index ]
        }
      })

      console.log(data)

      const res = await postGoodsPublish(data)
      const resp = await this.sendImage(commodityId)

      console.log(resp)
      this.showModal = false

      /**
		 * 成功提示
		 */

      this.$refs.uToast.show({
        type: 'success',
        title: '添加成功',
        message: '添加成功',
        iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/default.png'
      })

      this.$emit('changeIndex')
    },
    async sortationAttrConfirm(e) {
      console.log(e)
      if (this.sortation !== e.value[ 0 ]) {
        this.attributeList = []
        this.valueList = []
        this.sortation = e.value[ 0 ]
        const res = (await getAttributeByTypeId({ belongingType: e.indexs[ 0 ] + 1 })).data

        console.log(res, 'sreresresrse')
        this.currentType = e.indexs[ 0 ] + 1
        console.log(this.currentType)
        this.attributes = res
        this.attributeList = res && res.map(item => {
          const list = []

          list.push(item.attributeValueList && item.attributeValueList.map(atr => atr.value))
          return list
        })
        this.valueList = new Array(this.attributes.length)
      }
    },
    async sortationConfirm(e) {
      console.log(e, 'e')
      this.valueList[ e.myKey ] = e.value[ 0 ]
    },
    closeModal() {
      this.showmsg = false
      this.showMall = false
    },

    // 删除图片
    deletePic(event) {
      this[ `fileList${ event.name }` ].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      const lists = [].concat(event.file)
      const { commodityId } = this

      const fileListLen = this[ `fileList${ event.name }` ].length

      lists.map((item) => {
        this[ `fileList${ event.name }` ].push({
          ...item,
          // status: 'uploading',
          // message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        this.filePathList.push(lists[ i ].url)
      }
    },
    uploadFilePromise(url, commodityId, index) {
      const token = getToken()

      return new Promise((resolve, reject) => {
        const a = uni.uploadFile({
          url: 'https://skillgo.cn/test/shopping/commodityDetailPicture',
          filePath: url,
          name: 'file',
          header: {
            'content-type': 'multipart/form-data',
            'token': '9FFF2C5D959A3DBBC139AFE571DEF0327FF902C4070C2F5DEE7B73FF7A7ABFDD'
          },
          formData: {
            'num': index,
            'commodityId': commodityId
          },
          success: (res) => {
            resolve(res.data.data)
            console.log(res)
          }
        })
      })
    },
    sendImage(commodityId) {
      return new Promise((resolve, reject) => {
        this.filePathList.forEach(async(item, index) => {
          const _result = await this.uploadFilePromise(item, commodityId, index)

          resolve(_result)
          console.log(index)
        })
      })
    }
  },
}
</script>
<style lang="scss" scoped>
.pupImage{
	width: 100%;
}
	.good-publish {
		padding: 0 32rpx ;
		padding-top: 160rpx;
		.publish-bar {
			padding: 32rpx 0 ;
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			// align-items: flex-start;
			text-align: left;
			text {
				text-align: left;
				padding-left: 32rpx;
				font-size: 24rpx;
				color: #b5b5b5;
			}
		}

		.upload-box {
			margin-left: 37rpx;
			margin-top: 48rpx;
			margin-bottom: 18rpx;
			display: flex;
			flex-direction: row;
			justify-content: flex-start;
		}
	}

	.cf-button {
		position: fixed;
		bottom: 130rpx;
		background: #fff;
		width: 100%;
	}
	.infoshop {
		margin-left: 8rpx;
	}

	.info-bar {
		padding: 24rpx 0;

		.title {
			font-size: 36rpx;
			margin-bottom: 8rpx;
			font-weight: 500;
			color: #000000;
			display: flex;
			flex-direction: row;
	}
		.publInfo-table {
			display: flex;
			flex-direction: column;
			.table-row {
				width: 100wh;
				padding:27rpx 0;
				display: flex;
				flex-direction: row;
				.text {
					width: 18%;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					color: #000000;
					font-size: 28rpx;
					white-space: nowrap;
				}

				.button {
					flex: 1;
					.gridText {
						color: #c5c5c5;
					}
				}
				.input-bar {
					flex: 1;
					border-radius: 38rpx;
					border: 2rpx solid #3A62E9;
					margin-left: 32rpx;
					height: 50rpx;
					display: flex;
					align-items: center;
					.chose-input {
						height: 50rpx;
						width: 100%;
					}
				}
			}
		}
	}

	.scroll {
		height: calc(100vh - 294rpx);
	}

	.text-title {
		display: flex;
		justify-content: center;
		font-size: 36rpx;
		font-weight: 600;
	}

	.price-info {
		padding: 24rpx 0;
	}

	.true-price {
		display: flex;
		justify-content: space-between;
		.image {
			display: flex;
			flex-direction: row;
			.leftsellprice {
			margin-left: 8rpx;
			font-size: 36rpx;
			color: #000000;
			}
		}
		.right-price {
			display: flex;
			flex-direction: row;
			align-items: center;
			.right {
				padding-right: 10rpx;
				font-size: 36rpx;
				color: #EC493B;
			}
		}

	}

.old-price {
	display: flex;
	justify-content: space-between;
	padding-bottom:130rpx;
	.left {
		margin-left: 55rpx;
		font-size: 35rpx;
		color: #000000;
	}
	.right {
		font-size: 32rpx;
		color: #9D9D9D;
	}
}
.modal {
	text-align: center;
}
.pop {
	width: 400rpx;
	height: 240rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-around;
}
</style>
